# -*- coding: utf-8 -*-

###########################################################################
## Python code generated with wxFormBuilder (version Aug 24 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################

import re
import wx
import wx.xrc
import wx.grid
import logging
import datetime
from src.bridge.getsqldata import MysqlData
from src.bridge.getconfdata import ConfData

logging.basicConfig(level=logging.INFO)


###########################################################################
## Class KanBanPanel
###########################################################################

class KanBanPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(742, 440),
                          style=wx.TAB_TRAVERSAL)
        self.cfd = ConfData()
        self.md = MysqlData()
        self.colables = ["未开始", "进行中", "已暂停", "已完成", "已取消", "已关闭"]

        bSizer = wx.BoxSizer(wx.VERTICAL)

        gbSizer = wx.GridBagSizer(0, 0)
        gbSizer.SetFlexibleDirection(wx.BOTH)
        gbSizer.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        self.cm_staticText = wx.StaticText(self, wx.ID_ANY, u"数据来源方式：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.cm_staticText.Wrap(-1)
        gbSizer.Add(self.cm_staticText, wx.GBPosition(0, 0), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        cm_value = '数据库' if self.cfd.get_one_value(section='base', key='datacome') == '0' else '爬虫'
        self.cm_textCtrl = wx.TextCtrl(self, wx.ID_ANY, cm_value, wx.DefaultPosition, wx.DefaultSize, 0)
        self.cm_textCtrl.Enable(False)

        gbSizer.Add(self.cm_textCtrl, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.user_staticText = wx.StaticText(self, wx.ID_ANY, u"禅道用户：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.user_staticText.Wrap(-1)
        gbSizer.Add(self.user_staticText, wx.GBPosition(0, 2), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 5)

        user_value = self.cfd.get_one_value(section='ztinfo', key='user')
        self.user_textCtrl = wx.TextCtrl(self, wx.ID_ANY, user_value, wx.DefaultPosition, wx.DefaultSize, 0)
        self.user_textCtrl.Enable(False)

        gbSizer.Add(self.user_textCtrl, wx.GBPosition(0, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        self.zt_staticText = wx.StaticText(self, wx.ID_ANY, u"禅道地址：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.zt_staticText.Wrap(-1)
        gbSizer.Add(self.zt_staticText, wx.GBPosition(0, 4), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        zturl_value = self.cfd.get_one_value(section='ztinfo', key='url')
        self.zt_textCtrl = wx.TextCtrl(self, wx.ID_ANY, zturl_value, wx.DefaultPosition, wx.Size(360, -1), 0)
        self.zt_textCtrl.Enable(False)

        gbSizer.Add(self.zt_textCtrl, wx.GBPosition(0, 5), wx.GBSpan(1, 3),
                    wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)

        self.pd_staticText = wx.StaticText(self, wx.ID_ANY, u"产品名称：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.pd_staticText.Wrap(-1)
        gbSizer.Add(self.pd_staticText, wx.GBPosition(1, 0), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        prd_value = self.cfd.get_one_value(section='ztinfo', key='prdouct_cn')
        self.pd_textCtrl = wx.TextCtrl(self, wx.ID_ANY, prd_value, wx.DefaultPosition, wx.Size(120, -1), 0)
        self.pd_textCtrl.Enable(False)

        gbSizer.Add(self.pd_textCtrl, wx.GBPosition(1, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.pj_staticText = wx.StaticText(self, wx.ID_ANY, u"项目名称：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.pj_staticText.Wrap(-1)
        gbSizer.Add(self.pj_staticText, wx.GBPosition(1, 2), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 5)

        pj_value = self.cfd.get_one_value(section='ztinfo', key='project_cn')
        self.pj_textCtrl = wx.TextCtrl(self, wx.ID_ANY, pj_value, wx.DefaultPosition, wx.Size(120, -1), 0)
        self.pj_textCtrl.Enable(False)

        gbSizer.Add(self.pj_textCtrl, wx.GBPosition(1, 3), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.prdplan_staticText = wx.StaticText(self, wx.ID_ANY, u"产品计划：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.prdplan_staticText.Wrap(-1)
        gbSizer.Add(self.prdplan_staticText, wx.GBPosition(1, 4), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 5)

        prd_plan = self.cfd.get_one_value(section='ztinfo', key='product_plan')
        self.prdplan_textCtrl = wx.TextCtrl(self, wx.ID_ANY, prd_plan, wx.DefaultPosition, wx.Size(120, -1), 0)
        self.prdplan_textCtrl.Enable(False)

        gbSizer.Add(self.prdplan_textCtrl, wx.GBPosition(1, 5), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.pjversion_staticText = wx.StaticText(self, wx.ID_ANY, u"项目版本：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.pjversion_staticText.Wrap(-1)
        gbSizer.Add(self.pjversion_staticText, wx.GBPosition(1, 6), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL, 5)

        pj_version = self.cfd.get_one_value(section='ztinfo', key='project_version')
        self.pjversion_textCtrl = wx.TextCtrl(self, wx.ID_ANY, pj_version, wx.DefaultPosition, wx.Size(120, -1), 0)
        self.pjversion_textCtrl.Enable(False)

        gbSizer.Add(self.pjversion_textCtrl, wx.GBPosition(1, 7), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.cond_staticText = wx.StaticText(self, wx.ID_ANY, u"条件：", wx.DefaultPosition, wx.DefaultSize, 0)
        self.cond_staticText.Wrap(-1)
        gbSizer.Add(self.cond_staticText, wx.GBPosition(2, 0), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        cond_choice1Choices = [wx.EmptyString, u"类型", u"优先级", u"名称", u"日期"]
        self.cond_choice1 = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, cond_choice1Choices, 0)
        self.cond_choice1.SetSelection(0)
        gbSizer.Add(self.cond_choice1, wx.GBPosition(2, 1), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        cond_choice2Choices = [u"=", u"like", u"<", u">"]
        self.cond_choice2 = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, cond_choice2Choices, 0)
        self.cond_choice2.SetSelection(0)
        gbSizer.Add(self.cond_choice2, wx.GBPosition(2, 2), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 5)

        self.cond_textCtrl = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)
        gbSizer.Add(self.cond_textCtrl, wx.GBPosition(2, 3), wx.GBSpan(1, 2),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        self.refer_button = wx.Button(self, wx.ID_ANY, u"更 新", wx.DefaultPosition, wx.DefaultSize, 0)

        self.refer_button.SetDefault()
        gbSizer.Add(self.refer_button, wx.GBPosition(2, 6), wx.GBSpan(1, 1),
                    wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)

        bSizer.Add(gbSizer, 0, wx.EXPAND, 5)

        self.table_grid = wx.grid.Grid(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0)

        # Grid
        self.mr, self.dictvalue = self._get_data()
        self.table_grid.CreateGrid(self.mr, 6) if self.mr > 10 else self.table_grid.CreateGrid(10, 6)
        self.table_grid.EnableEditing(False)
        self.table_grid.EnableGridLines(True)
        self.table_grid.EnableDragGridSize(False)
        self.table_grid.SetMargins(0, 0)

        # Columns
        self.table_grid.EnableDragColMove(False)
        self.table_grid.EnableDragColSize(True)
        self.table_grid.SetColLabelSize(30)
        self._set_cols_lable()
        self.table_grid.SetColLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)

        # Rows
        self.table_grid.EnableDragRowSize(True)
        self.table_grid.SetRowLabelSize(30)
        for r in range(self.mr):
            self.table_grid.SetRowSize(r, 150)
        self.table_grid.SetRowLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)

        # Label Appearance

        # Cell Defaults
        self.table_grid.SetDefaultCellAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)
        bSizer.Add(self.table_grid, 0, wx.ALL | wx.EXPAND, 5)

        self.SetSizer(bSizer)
        self.Layout()
        self.render_table_value(self.dictvalue)

        # Connect Events
        self.refer_button.Bind(wx.EVT_BUTTON, self.refer_table_value)

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def refer_table_value(self, event):
        event.GetEventObject().Disable()
        try:
            cm_value = '数据库' if self.cfd.get_one_value('base', 'datacome') == '0' else '爬虫'
            self.cm_textCtrl.SetValue(cm_value)
            user = self.cfd.get_one_value('ztinfo', 'user') if self.cfd.get_one_value('ztinfo', 'user') else ''
            self.user_textCtrl.SetValue(user)
            product = self.cfd.get_one_value('ztinfo', 'prdouct_cn') if self.cfd.get_one_value('ztinfo',
                                                                                               'prdouct_cn') else ''
            self.pd_textCtrl.SetValue(product)
            project = self.cfd.get_one_value('ztinfo', 'project_cn') if self.cfd.get_one_value('ztinfo',
                                                                                               'project_cn') else ''
            self.pj_textCtrl.SetValue(project)
            prdplan = self.cfd.get_one_value('ztinfo', 'product_plan') if self.cfd.get_one_value('ztinfo',
                                                                                                 'product_plan') else ''
            self.prdplan_textCtrl.SetValue(prdplan)
            prjversion = self.cfd.get_one_value('ztinfo', 'project_version') if self.cfd.get_one_value('ztinfo',
                                                                                                       'project_version') else ''
            self.pjversion_textCtrl.SetValue(prjversion)
            mxrow = 0
            dictvalue = {}
            dictkey = {'优先级': 'pri', '名称': 'title', '日期': 'deadline'}
            cond1 = self.cond_choice1.GetStringSelection()
            if cond1:
                cond2 = self.cond_choice2.GetStringSelection()
                condtext = self.cond_textCtrl.GetValue()
                if cond1 == '类型':
                    if str(condtext).lower() in ['story', '需求']:
                        row, dictvalue['stroylist'] = self.md.get_story_data(product, user, prdplan)
                    elif str(condtext).lower() in ['task', '任务']:
                        row, dictvalue['tasklist'] = self.md.get_task_data(project, user)
                    elif str(condtext).lower() in ['bug', '缺陷']:
                        row, dictvalue['buglist'] = self.md.get_bug_data(product, user)
                    else:
                        wx.MessageBox("条件为类型时， 只能搜索 需求、story、任务、task、缺陷、bug，请检查输入！")
                        exit(1001)
                    mxrow = max(row.values())
                elif cond1 == '优先级':
                    mxrow, dictvalue = self._get_data(condition="{} {} '{}'".format(dictkey['优先级'], cond2, condtext))
                elif cond1 == '名称':
                    if cond2 == 'like':
                        stdict, dictvalue['stroylist'] = self.md.get_story_data(product, user, prdplan,
                                                                                condition="{} like '%{}%'".format(
                                                                                    dictkey['名称'], condtext))
                        tdict, dictvalue['tasklist'] = self.md.get_task_data(project, user,
                                                                             condition="{} like '%{}%'".format('name',
                                                                                                               condtext))
                        bdict, dictvalue['buglist'] = self.md.get_bug_data(product, user,
                                                                           condition="{} like '%{}%'".format(
                                                                               dictkey['名称'], condtext))
                        for stb in [stdict, tdict]:
                            for key, val in stb.items():
                                bdict[key] += val
                        mxrow = max(bdict.values())
                    else:
                        stdict, dictvalue['stroylist'] = self.md.get_story_data(product, user, prdplan,
                                                                                condition="{} {} '{}'".format(
                                                                                    dictkey['名称'], cond2, condtext))
                        tdict, dictvalue['tasklist'] = self.md.get_task_data(project, user,
                                                                             condition="{} {} '{}'".format('name',
                                                                                                           cond2,
                                                                                                           condtext))
                        bdict, dictvalue['buglist'] = self.md.get_bug_data(product, user,
                                                                           condition="{} {} '{}'".format(dictkey['名称'],
                                                                                                         cond2,
                                                                                                         condtext))
                        for stb in [stdict, tdict]:
                            for key, val in stb.items():
                                bdict[key] += val
                        mxrow = max(bdict.values())
                elif cond1 == '日期':
                    cond2 = '=' if cond2 == 'like' else cond2
                    stdict, dictvalue['stroylist'] = self.md.get_story_data(product, user, prdplan,
                                                                            condition="{} {} '{}'".format(
                                                                                'lastEditedDate', cond2, condtext))
                    tdict, dictvalue['tasklist'] = self.md.get_task_data(project, user,
                                                                         condition="{} {} '{}'".format(dictkey['日期'],
                                                                                                       cond2,
                                                                                                       condtext))
                    bdict, dictvalue['buglist'] = self.md.get_bug_data(product, user,
                                                                       condition="{} {} '{}'".format(dictkey['日期'],
                                                                                                     cond2,
                                                                                                     condtext))
                    for stb in [stdict, tdict]:
                        for key, val in stb.items():
                            bdict[key] += val
                    mxrow = max(bdict.values())
            else:
                mxrow, dictvalue = self._get_data()
            self.table_grid.Update()
            self.table_grid.InsertRows(-1, int(mxrow - 10)) if mxrow - 10 > 0 else logging.info(mxrow)
            self.table_grid.ClearGrid()
            self.render_table_value(dictvalue)
        except BaseException as e:
            logging.error(e)
        finally:
            event.GetEventObject().Enable()
        event.Skip()

    def _set_cols_lable(self):
        try:
            for c in range(len(self.colables)):
                self.table_grid.SetColLabelValue(c, self.colables[c])
                self.table_grid.SetColSize(c, 150)
        except BaseException as e:
            logging.error(e)

    def _get_data(self, condition='1=1'):
        try:
            product = self.pd_textCtrl.GetValue()
            project = self.pj_textCtrl.GetValue()
            user = self.user_textCtrl.GetValue()
            users = re.split('[,./\\;-=_+，。；‘、】【\[\]}{:|<>]+', user)  # 用于支持用户未多个的情况
            plan = self.prdplan_textCtrl.GetValue()
            dcome = self.cfd.get_one_value('base', 'datacome')
            dictvalue = {}
            if dcome == '0':
                stdict, dictvalue['stroylist'] = self.md.get_story_data(product, user, plan, condition)
                tdict, dictvalue['tasklist'] = self.md.get_task_data(project, user, condition)
                bdict, dictvalue['buglist'] = self.md.get_bug_data(product, user, condition)
                for stb in [stdict, tdict]:
                    for key, val in stb.items():
                        bdict[key] += val
                logging.info("========={}".format(bdict))
                logging.info("===maxvalue==={}".format(max(bdict.items())))
                logging.info("========={}".format(dictvalue))
                return max(bdict.values()), dictvalue
            else:
                opt = self.cfd.get_one_value('base', 'opt')
                url = self.cfd.get_one_value('ztinfo', 'url')
                pwd = self.cfd.get_one_value('ztinfo', 'pwd')
                from src.bridge.scrapydata import ScrapyData
                sd = ScrapyData(url, users[0], pwd, product, project, opt, all=len(users))
                mrow, dictvalue = sd.scrapy_data()
                sd.dr.close()
                return mrow, dictvalue
        except BaseException as e:
            logging.error(e)

    def render_table_value(self, dictvalue):
        """
        获取需求数据
        :return:
        """
        try:
            if isinstance(dictvalue, dict):
                for dicv in dictvalue.values():
                    if dicv != 0:
                        for ls in dicv:
                            coln = self.colables.index(ls[0])
                            value = "\n".join(["  ".join(ls[1:-2]), str(ls[-2]), "    " * 3 + ls[-1]])
                            for r in range(len(ls)):
                                cellvalue = self.table_grid.GetCellValue(row=r, col=coln)
                                if cellvalue:
                                    pass
                                elif ls[-1] < str(datetime.date.today()) and ls[0] in ['未开始', '进行中']:
                                    # 当数据中的完成时间，小于当前日期，同时 数据的状态为‘未开始 进行中’说明已经延期，延期的用红色文字，这样支持换行
                                    self.table_grid.SetCellTextColour(r, coln, 'red')
                                    render = wx.grid.GridCellAutoWrapStringRenderer()
                                    self.table_grid.SetCellRenderer(r, coln, render)
                                    self.table_grid.SetCellValue(r, coln, value)
                                    break
                                else:
                                    # 表格单元格可能之前被设置成红色了， 所以需要再次渲染成默认，支持换行
                                    self.table_grid.SetCellTextColour(r, coln, 'black')
                                    render = wx.grid.GridCellAutoWrapStringRenderer()
                                    self.table_grid.SetCellRenderer(r, coln, render)
                                    self.table_grid.SetCellValue(r, coln, value)
                                    break
        except BaseException as e:
            logging.error(e)
